﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using ADODB;
using System.Net;

namespace Orders_Collect
{
    public partial class frmCollect : Form
    {
        public frmCollect()
        {
            InitializeComponent();
        }
        Boolean nFlag = false;
        DataSet ds = new DataSet();
        List<string> ls = new List<string>();
        List<string> ls_file = new List<string>();
        List<string> ls_print = new List<string>();
        int nLogin=0;  //判断登陆错误次数
        string spath = System.IO.Path.Combine(Application.StartupPath, "LocalSetting.xml");
        private void frmCollect_Load(object sender, EventArgs e)
        {
            string aa = "";
            //1、加载配置信息
            //string lspath = System.IO.Path.Combine(Application.StartupPath, "LocalSetting.xml");
            ds.ReadXml(spath);

            ////如果停用则不执行
            //if (ds.Tables[0].Rows[0]["start"].ToString().ToUpper()=="TRUE")
            //{
            //    //Application.Exit;
            //}

            ////获取本地存放路径
            //string lsdate = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            //string lsdir = System.IO.Path.Combine(ds.Tables[0].Rows[0]["add1"].ToString(), lsdate);
            //if (System.IO.Directory.Exists(lsdir) == false)
            //{
            //    System.IO.Directory.CreateDirectory(lsdir);
            //}


            //2、加载登陆页面，并登陆
            this.Text = "订单采集服务端(" + ds.Tables[0].Rows[0]["title"].ToString() + ")";
            this.wb1.Navigate(ds.Tables[0].Rows[0]["login"].ToString());
            Delay(9000);
            this.Start();

            #region  采集信息
            /*
            //if (nFlag == true)
            //{
            //    try
            //    {
            //        //3、获取订单清单
            //        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //        doc.LoadHtml(this.wb1.Document.All[0].InnerHtml);
            //        //doc.OverrideEncoding = Encoding.GetEncoding("gb2312"); 
            //        HtmlAgilityPack.HtmlNode nodes = doc.DocumentNode;
            //        HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("//*[@id=\"pusListTab\"]/tbody/tr/td/a");
            //        foreach (HtmlAgilityPack.HtmlNode item in node_tr)
            //        {
            //            Regex reg = new Regex(@"(\d+(\.\d+)?)", RegexOptions.None);
            //            ls.Add(reg.Matches(item.OuterHtml)[0].Value);

            //        }

            //    }
            //    catch (Exception ex)
            //    {
            //        ds.Tables[0].Rows[0]["start"] = "True";
            //        ds.Tables[0].WriteXml(spath);
            //        Collect_Pub.App.ErrLog(ex.ToString());
            //        Collect_Pub.App.Mail_Send("lik.li@likelic.com;Bob.He@magna.com"
            //    , ds.Tables[0].Rows[0]["email_user"].ToString()
            //    , ds.Tables[0].Rows[0]["send_email"].ToString().Trim()
            //    , ""
            //    , lsdate + "登陆错误"
            //    , "Dear ALL:<br>" + lsdate + "登陆错误，请及时停止服务！" + ds.Tables[0].Rows[0]["login"].ToString()
            //    , ls
            //    , ds.Tables[0].Rows[0]["email_smtp"].ToString()
            //    , ds.Tables[0].Rows[0]["email_user"].ToString()
            //    , ds.Tables[0].Rows[0]["email_pwd"].ToString()
            //    );

            //        throw;
            //    }
            //}

            ////4、根据订单清单获取详细页面
            //try
            //{
            //    //5、保存页面到本地
            //    for (int i = 0; i < ls.Count; i++)
            //    {

            //        string lsfile = System.IO.Path.Combine(lsdir, "" + ls[i].ToString() + ".mht");
            //        CDO.Message message = new CDO.MessageClass();
            //        ADODB.Stream stream = null;
            //        this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            //        message.MimeFormatted = true;
            //        message.CreateMHTMLBody(ds.Tables[0].Rows[0]["detail"].ToString().Replace("{0}", ls[0].ToString()), CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
            //        stream = message.GetStream();
            //        stream.SaveToFile(lsfile, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);
            //        message = null;
            //        this.Cursor = System.Windows.Forms.Cursors.Default;
            //        ls_file.Add(lsfile);
            //    }


            //    //6、保存页面到共享文件夹

            //    if (ds.Tables[0].Rows[0]["add2"].ToString().Trim() != "")
            //    {
            //        string lspath2 = System.IO.Path.Combine(ds.Tables[0].Rows[0]["add2"].ToString().Trim(), lsdate);
            //        if (System.IO.Directory.Exists(lspath2) == false)
            //        {
            //            System.IO.Directory.CreateDirectory(lspath2);
            //        }
            //        string[] ls = System.IO.Directory.GetFiles(lspath);
            //        for (int i = 0; i < ls_file.Count; i++)
            //        {
            //            string lsfile2 = System.IO.Path.Combine(lspath2, System.IO.Path.GetFileName(ls[i]).ToString());
            //            System.IO.File.Copy(ls_file[i], lsfile2, true);
            //        }

            //    }

            //    //7、发送邮件
            //    if (ds.Tables[0].Rows[0]["send_email"].ToString().Trim() != "")
            //    {
            //        Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
            //        , ds.Tables[0].Rows[0]["email_user"].ToString()
            //        , ds.Tables[0].Rows[0]["send_email"].ToString().Trim()
            //        , ""
            //        , lsdate + "订单采集"
            //        , "Dear ALL:<br>" + lsdate + "订单采集内容请见附件！"
            //        , ls_file
            //        , ds.Tables[0].Rows[0]["email_smtp"].ToString()
            //        , ds.Tables[0].Rows[0]["email_user"].ToString()
            //        , ds.Tables[0].Rows[0]["email_pwd"].ToString()
            //        );

            //    }

            //    //8、解析详细页面内容
            //    DataTable ldt_head = new DataTable();
            //    ldt_head.Columns.Add("no");
            //    ldt_head.Columns.Add("receipt");
            //    ldt_head.Columns.Add("receipt_date");
            //    ldt_head.Columns.Add("remark");
            //    ldt_head.Columns.Add("key");


            //    DataTable ldt_detail = new DataTable();
            //    ldt_detail.Columns.Add("sku");
            //    ldt_detail.Columns.Add("sku_magna");
            //    ldt_detail.Columns.Add("qty");
            //    ldt_detail.Columns.Add("key");

            //    for (int i = 0; i < ls.Count; i++)
            //    {
            //        DataRow ldr_head = ldt_head.NewRow();
            //        ldr_head["key"] = i;
            //        string lsfile = System.IO.Path.Combine(lsdir, "" + ls[i].ToString() + ".mht");
            //        string lshtml = System.IO.File.ReadAllText(lsfile, Encoding.GetEncoding("GB2312"));
            //        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //        doc.LoadHtml(lshtml);
            //        HtmlAgilityPack.HtmlNode nodes = doc.DocumentNode;
            //        HtmlAgilityPack.HtmlNodeCollection node_no = nodes.SelectNodes("//*[@face=\"C39P36DmTt\"]");
            //        if (node_no.Count > 0)
            //        {
            //            ldr_head["no"] = node_no[0].InnerText.ToString().Replace("*", "");
            //        }
            //        HtmlAgilityPack.HtmlNodeCollection node_receipt = nodes.SelectNodes("/html/body/table/tr/td/table[3]/tbody/tr");
            //        if (node_receipt.Count > 10)
            //        {
            //            string[] ls_receipt = node_receipt[1].InnerText.ToString().Split(new char[] { '\r', '\n' });
            //            ldr_head["receipt"] = ls_receipt[10].ToString().Replace("\t", "").Replace("<br>", "");
            //            ls_receipt = node_receipt[2].InnerText.ToString().Split(new char[] { '\r', '\n' });
            //            ldr_head["receipt_date"] = ls_receipt[10].ToString().Replace("\t", "").Replace("&nbsp;&nbsp;", " ");
            //            ls_receipt = node_receipt[8].InnerText.ToString().Split(new char[] { '\r', '\n' });
            //            ldr_head["remark"] = ls_receipt[12].ToString().Replace("\t", "");
            //        }
            //        ldt_head.Rows.Add(ldr_head);
            //        HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("/html/body/table/tr/td/table[5]/tbody/tr");
            //        for (int j = 2; j < node_tr.Count; j++)
            //        {

            //            string lsvalue = node_tr[j].InnerText;
            //            string[] lsvalues = lsvalue.ToString().Split(new char[] { '\r', '\n' });
            //            if (lsvalues.Length > 7)
            //            {
            //                DataRow ldr_detail = ldt_detail.NewRow();
            //                ldr_detail["key"] = i;
            //                ldr_detail["sku"] = lsvalues[4].Replace("\t", "").ToString().Trim();
            //                ldr_detail["qty"] = lsvalues[8].Replace("\t", "").ToString().Trim();
            //                ldt_detail.Rows.Add(ldr_detail);
            //            }

            //        }

            //    }


            //    //9、生成出货单
            //    List<string> ls_sql = new List<string>();
            //    DataTable ldt_link = App.SQLHelper.GetDataTable(this.ds.Tables[0].Rows[0]["conn"].ToString(), "select * from sku_link", "link");
            //    DataTable ldt_sku = App.SQLHelper.GetDataTable(this.ds.Tables[0].Rows[0]["conn"].ToString(), "select * from sku", "sku");
            //    string lsflag = ldt_head.Rows[0]["no"].ToString().Split('-')[0].ToString();
            //    if (this.ds.Tables[0].Rows[0]["conn"].ToString() != "")
            //    {
            //        for (int i = 0; i < ldt_head.Rows.Count; i++)
            //        {
            //            string lsfactory = "001";
            //            string lswhseid = "wh1";
            //            if (this.ds.Tables[0].Rows[0]["factory"].ToString() == "KS")
            //            {
            //                lsfactory = "001";
            //                lswhseid = "wh1";
            //            }
            //            else if (this.ds.Tables[0].Rows[0]["factory"].ToString() == "KSND")
            //            {
            //                lsfactory = "019";
            //                lswhseid = "wh2";
            //            }
            //            string lsorderkey = App.SQLHelper.ExecuteScalar(this.ds.Tables[0].Rows[0]["conn"].ToString(), CommandType.Text, "DECLARE @key varchar(50) exec pro_GetOrderNo '" + lswhseid + "','" + lsfactory + "IB','ORDERKEY','出货单号',@key OUTPUT select @key as orderkey ", new System.Data.SqlClient.SqlParameter("", "")).ToString();//调用存储过程pro_GetOrderNo生成出货单号
            //            string lsSql = "insert into orders(whseid,orderkey,customer_code,delivery_order,status,type,priority,data_from,requestshipdate,grossweight";
            //            lsSql += ",netweight,cube,plt,ctn,pcs,udf1,udf2,udf3,udf4,remark,product,addwho,adddate) values ";
            //            lsSql += "('" + lswhseid + "','" + lsorderkey + "','" + this.ds.Tables[0].Rows[0]["factory"].ToString() + "','" + ldt_head.Rows[0]["no"].ToString() + "','01','01','02'";
            //            lsSql += ",'采集新增','" + ldt_head.Rows[0]["receipt_date"].ToString() + "'";
            //            lsSql += ", 0,0,0,0,0,0";
            //            lsSql += ",'','','',''";
            //            lsSql += ",'" + ldt_head.Rows[0]["remark"].ToString() + "','1','System','" + System.DateTime.Now.ToString() + "')";
            //            ls_sql.Add(lsSql);
            //            DataRow[] ldrs = ldt_detail.Select("key='" + ldt_head.Rows[i]["key"].ToString() + "'");
            //            for (int j = 0; j < ldrs.Length; j++)
            //            {
            //                string lssku = "";
            //                string lssku_descr = "";
            //                string lssku_unit = "";
            //                DataRow[] ldrs_link = ldt_link.Select("customer_sku='" + ldrs[j]["sku"].ToString() + "' and factory_code='" + lsflag + "'");
            //                if (ldrs_link.Length == 1)
            //                {
            //                    lssku = ldrs_link[0]["sku"].ToString();
            //                    DataRow[] ldrs_sku = ldt_sku.Select("sku='" + lssku + "' and whseid='" + lswhseid + "'");
            //                    if (ldrs_sku.Length == 1)
            //                    {
            //                        lssku_descr = ldrs_sku[0]["description"].ToString();
            //                        lssku_unit = ldrs_sku[0]["unit"].ToString();
            //                    }
            //                }
            //                else
            //                {
            //                    lssku = ldrs[j]["sku"].ToString();
            //                }

            //                lsSql = "insert into orderdetail(whseid,orderkey,line_no,customer_code,sku,skudescr,status,pre_qty,act_qty,allocated_qty,picked_qty,unshiped_qty,lottable01,lottable02,lottable03,lottable04,lottable05,lottable06,lottable07,lottable08,lottable09,lottable10";
            //                lsSql += ",uom,viceuom,udf1,udf2,udf3,udf4,remark,addwho,adddate) values ";
            //                lsSql += "('" + lswhseid + "','" + lsorderkey + "','" + (j + 1).ToString("D5") + "','" + this.ds.Tables[0].Rows[0]["factory"].ToString() + "','" + lssku + "','" + lssku_descr + "','01'";
            //                lsSql += "," + ldrs[j]["qty"].ToString() + ",0,0,0,0";
            //                lsSql += ",'','','','','','','" + ldrs[j]["sku"].ToString() + "'";
            //                lsSql += " ,'" + ldt_head.Rows[0]["receipt"].ToString() + "','','','" + lssku_unit + "','','','','',''";
            //                lsSql += ",'','System','" + System.DateTime.Now.ToString() + "')";
            //                ls_sql.Add(lsSql);
            //            }
            //        }

            //        App.SQLHelper.ExecuteSQLScriptLists(ls_sql, this.ds.Tables[0].Rows[0]["conn"].ToString());
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Collect_Pub.App.ErrLog(ex.ToString());
            //    throw;
            //}

            //Application.Exit();
             */
            #endregion
        }

        private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //this.wb1.Document.GetElementById("loginId").InnerText = ds.Tables[0].Rows[0]["user"].ToString();
            //this.wb1.Document.GetElementById("pwd").InnerText = ds.Tables[0].Rows[0]["pwd"].ToString();
            //int lncontrol = this.wb1.Document.Body.All.Count;
            //for (int i = 0; i < lncontrol; i++)
            //{

            //    if (this.wb1.Document.All[i].Name.ToString() == "loginId")
            //    {
            //        this.wb1.Document.All[i].SetAttribute("value", ds.Tables[0].Rows[0]["user"].ToString());
            //    }
            //    if (this.wb1.Document.All[i].Name.ToString() == "pwd")
            //    {
            //        string lspwd = ds.Tables[0].Rows[0]["pwd"].ToString();
            //        if (ds.Tables[0].Rows[0]["pwd_des"].ToString().ToUpper()=="TRUE")
            //        {
            //          lspwd=Collect_Pub.App.MD5Encrypt32(ds.Tables[0].Rows[0]["pwd"].ToString()).ToLower().Trim();
            //        }
            //        System.Threading.Thread.Sleep(2000);
            //        this.wb1.Document.All[i].SetAttribute("value", lspwd);
            //    }
            //}

            //HtmlElement formLogin = this.wb1.Document.Forms["formname"];
            //formLogin.InvokeMember("submit");
            //System.Threading.Thread.Sleep(5000);
            //this.wb1.Navigate(ds.Tables[0].Rows[0]["list"].ToString());
            //nFlag = true;

        }

        private void btnlogin_Click(object sender, EventArgs e)
        {




            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(this.wb1.Document.All[1].InnerHtml);
            HtmlAgilityPack.HtmlNode nodes = doc.DocumentNode;
       
          // HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("//*[@id=\"pusListTab\"]/tbody/tr/td/a");
            HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("//*[@id=\"tableBody\"]/div[3]/table/tbody/tr[1]/td[2]/div/a/span");
            if (node_tr == null)
            {
                return;
            }

            foreach (HtmlAgilityPack.HtmlNode item in node_tr)
            {
                Regex reg = new Regex(@"(\d+(\.\d+)?)", RegexOptions.None);
                ls.Add(reg.Matches(item.OuterHtml)[1].Value);

            }
            MessageBox.Show("OK");

        }

        private void wb2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string lsfile=System.IO.Path.Combine( ds.Tables[0].Rows[0]["add1"].ToString(),System.DateTime.Now.Year.ToString());
            lsfile = System.IO.Path.Combine(lsfile,  "1.html");

            //System.IO.File.WriteAllText(lsfile, this.wb2.Document.All[0].InnerHtml);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ls.Count; i++)
            {
            string lsfile = System.IO.Path.Combine(ds.Tables[0].Rows[0]["add1"].ToString(), System.DateTime.Now.Year.ToString());
            lsfile = System.IO.Path.Combine(lsfile, ""+ls[i].ToString()+".mht");

              //  this.wb2.Navigate(ds.Tables[0].Rows[0]["detail"].ToString().Replace("{0}",ls[0].ToString()));
               CDO.Message message = new CDO.MessageClass();
                        ADODB.Stream stream = null;
                        this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                        message.MimeFormatted = true;                       
                        message.CreateMHTMLBody(ds.Tables[0].Rows[0]["detail"].ToString().Replace("{0}",ls[i].ToString()), CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
                        stream = message.GetStream();
                        stream.SaveToFile(lsfile, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);                       
                        message = null;
                        this.Cursor = System.Windows.Forms.Cursors.Default;
                       
               // System.Threading.Thread.Sleep(3000);
            }
            MessageBox.Show("文件成功保存。");

            //MessageBox.Show("OK");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // DataTable ldt_head=new DataTable();
            //ldt_head.Columns.Add("no");
            //ldt_head.Columns.Add("receipt");
            //ldt_head.Columns.Add("receipt_date");
            //ldt_head.Columns.Add("remark");
            //DataRow ldr_head = ldt_head.NewRow();

            //DataTable ldt_detail=new DataTable();
            //ldt_detail.Columns.Add("sku");
            //ldt_detail.Columns.Add("sku_magna");
            //ldt_detail.Columns.Add("qty");
            //string lshtml = System.IO.File.ReadAllText(@"E:\测试文件\订单采集\2017\10573682.mht", Encoding.GetEncoding("GB2312"));
            //HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //doc.LoadHtml(lshtml);
            //HtmlAgilityPack.HtmlNode nodes = doc.DocumentNode;
            //HtmlAgilityPack.HtmlNodeCollection node_no = nodes.SelectNodes("//*[@face=\"C39P36DmTt\"]");
            //if (node_no.Count>0)
            //{
            //    ldr_head["no"] = node_no[0].InnerText.ToString().Replace("*","");
            //}
            //HtmlAgilityPack.HtmlNodeCollection node_receipt = nodes.SelectNodes("/html/body/table/tr/td/table[3]/tbody/tr");
            //if (node_receipt.Count>10)
            //{
            //     string[] ls_receipt = node_receipt[1].InnerText.ToString().Split(new char[] { '\r', '\n' });
            //     ldr_head["receipt"] = ls_receipt[10].ToString().Replace("\t","").Replace("<br>","");
            //     ls_receipt = node_receipt[2].InnerText.ToString().Split(new char[] { '\r', '\n' });
            //     ldr_head["receipt_date"] = ls_receipt[10].ToString().Replace("\t", "").Replace("&nbsp;&nbsp;", " ");
            //     ls_receipt = node_receipt[8].InnerText.ToString().Split(new char[] { '\r', '\n' });
            //     ldr_head["remark"] = ls_receipt[12].ToString().Replace("\t", "");
            //}
            //ldt_head.Rows.Add(ldr_head);
            //HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("/html/body/table/tr/td/table[5]/tbody/tr");
            //for (int i = 2; i < node_tr.Count; i++)
            //{
            //    string lsvalue = node_tr[i].InnerText;
            //    string[] lsvalues = lsvalue.ToString().Split(new char[] { '\r', '\n' });
            //    if (lsvalues.Length>7)
            //    {
            //        DataRow ldr_detail = ldt_detail.NewRow();
            //        ldr_detail["sku"] = lsvalues[4].Replace("\t", "").ToString().Trim();
            //        ldr_detail["qty"] = lsvalues[8].Replace("\t", "").ToString().Trim();
            //        ldt_detail.Rows.Add(ldr_detail);
            //    }
             
            //}

            //MessageBox.Show(ldt_head.Rows.Count.ToString());
        }


        private void Delay(int Millisecond) //延迟系统时间，但系统又能同时能执行其它任务；
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(Millisecond) > DateTime.Now)
            {
                Application.DoEvents();//转让控制权            
            }
            return;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Start();
           
        }


        private void Start()
        {

            #region  采集 数据 
     /*
            //this.wb1.Document.GetElementById("username").InnerText = ds.Tables[0].Rows[0]["user"].ToString();
            //this.wb1.Document.GetElementById("password").InnerText = ds.Tables[0].Rows[0]["pwd"].ToString();

            this.wb1.Document.GetElementById("loginId").InnerText = ds.Tables[0].Rows[0]["user"].ToString();
            this.wb1.Document.GetElementById("pwd").InnerText = ds.Tables[0].Rows[0]["pwd"].ToString();
            int lncontrol = this.wb1.Document.Body.All.Count;
            for (int i = 0; i < lncontrol; i++)
            {

                //if (this.wb1.Document.All[i].Name.ToString() == "username")
                //{
                //    this.wb1.Document.All[i].SetAttribute("value", ds.Tables[0].Rows[0]["user"].ToString());
                //}

                if (this.wb1.Document.All[i].Name.ToString() == "loginId")
                {
                    this.wb1.Document.All[i].SetAttribute("value", ds.Tables[0].Rows[0]["user"].ToString());
                }

                //if (this.wb1.Document.All[i].Name.ToString() == "password")
                //{
                //    string lspwd = ds.Tables[0].Rows[0]["pwd"].ToString();
                //    if (ds.Tables[0].Rows[0]["pwd_des"].ToString().ToUpper() == "TRUE")
                //    {
                //        lspwd = Collect_Pub.App.MD5Encrypt32(ds.Tables[0].Rows[0]["pwd"].ToString()).ToLower().Trim();
                //    }
                //    System.Threading.Thread.Sleep(4000);
                //    // System.Threading.Thread.Sleep(2000);
                //    this.wb1.Document.All[i].SetAttribute("value", lspwd);
                //}

                if (this.wb1.Document.All[i].Name.ToString() == "pwd")
                {
                    string lspwd = ds.Tables[0].Rows[0]["pwd"].ToString();
                    if (ds.Tables[0].Rows[0]["pwd_des"].ToString().ToUpper() == "TRUE")
                    {
                        lspwd = Collect_Pub.App.MD5Encrypt32(ds.Tables[0].Rows[0]["pwd"].ToString()).ToLower().Trim();
                    }
                    System.Threading.Thread.Sleep(4000);
                    // System.Threading.Thread.Sleep(2000);
                    this.wb1.Document.All[i].SetAttribute("value", lspwd);
                }




            }
            HtmlElement formLogin = this.wb1.Document.Forms["formname"];
            formLogin.InvokeMember("submit");
     */
            #endregion

            #region 采集信息NEW
        
            this.wb1.Document.GetElementById("username").InnerText = ds.Tables[0].Rows[0]["user"].ToString();
            this.wb1.Document.GetElementById("password").InnerText = ds.Tables[0].Rows[0]["pwd"].ToString();

            //this.wb1.Document.GetElementById("loginId").InnerText = ds.Tables[0].Rows[0]["user"].ToString();
            //this.wb1.Document.GetElementById("pwd").InnerText = ds.Tables[0].Rows[0]["pwd"].ToString();
            int lncontrol = this.wb1.Document.Body.All.Count;
            for (int i = 0; i < lncontrol; i++)
            {

                if (this.wb1.Document.All[i].Name.ToString() == "username")
                {
                    this.wb1.Document.All[i].SetAttribute("value", ds.Tables[0].Rows[0]["user"].ToString());
                }

                //if (this.wb1.Document.All[i].Name.ToString() == "loginId")
                //{
                //    this.wb1.Document.All[i].SetAttribute("value", ds.Tables[0].Rows[0]["user"].ToString());
                //}

                if (this.wb1.Document.All[i].Name.ToString() == "password")
                {
                    string lspwd = ds.Tables[0].Rows[0]["pwd"].ToString();
                    //if (ds.Tables[0].Rows[0]["pwd_des"].ToString().ToUpper() == "TRUE")
                    //{
                    //    lspwd = Collect_Pub.App.MD5Encrypt32(ds.Tables[0].Rows[0]["pwd"].ToString()).ToLower().Trim();
                    //}
                   // System.Threading.Thread.Sleep(4000);
                    System.Threading.Thread.Sleep(8000);
                    // System.Threading.Thread.Sleep(2000);
                    this.wb1.Document.All[i].SetAttribute("value", lspwd);
                }

                //if (this.wb1.Document.All[i].Name.ToString() == "pwd")
                //{
                //    string lspwd = ds.Tables[0].Rows[0]["pwd"].ToString();
                //    if (ds.Tables[0].Rows[0]["pwd_des"].ToString().ToUpper() == "TRUE")
                //    {
                //        lspwd = Collect_Pub.App.MD5Encrypt32(ds.Tables[0].Rows[0]["pwd"].ToString()).ToLower().Trim();
                //    }
                //    System.Threading.Thread.Sleep(4000);
                //    // System.Threading.Thread.Sleep(2000);
                //    this.wb1.Document.All[i].SetAttribute("value", lspwd);
                //}
  
               


            }
         
            //HtmlElement formLogin = this.wb1.Document.Forms["formname"];
            //formLogin.InvokeMember("submit");

            HtmlElement buttonSubmit = this.wb1.Document.GetElementById("J_sidebar_login");
            buttonSubmit.InvokeMember("click");// 提交登录
            System.Threading.Thread.Sleep(6000);

          

            //HtmlElement buttonignore = this.wb1.Document.GetElementById("ignore");
            //buttonignore.InvokeMember("click");
            //System.Threading.Thread.Sleep(12000);
            this.wb1.Navigate(ds.Tables[0].Rows[0]["list"].ToString());
            #endregion


            //System.Threading.Thread.Sleep(6000);
           // System.Threading.Thread.Sleep(5000);
             // wb1.Navigate("https://idp.saic-gm.com/sgm-universe-eaiweb/Authn/TAMUserPassAuth");
          //  wb1.Navigate("http://eschedule.shanghaigm.com/JQ/jsp/common/index.jsp");
          //  HtmlElement buttonignore = this.wb1.Document.GetElementById("ignore");
            //HtmlElement buttonignore = this.wb1.Document.GetElementById("ignore");
            //buttonignore.InvokeMember("click");
           // this.wb1.Navigate(ds.Tables[0].Rows[0]["list"].ToString());

            nFlag = true;
            this.timer1.Enabled = true;
            this.timer1.Interval = Convert.ToInt32(ds.Tables[0].Rows[0]["list1_time"].ToString()) * 60 * 1000;
            this.timer2.Enabled = true;
            this.timer2.Interval = Convert.ToInt32(ds.Tables[0].Rows[0]["list_time"].ToString()) * 60 * 1000;
            //this.button3.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = Collect_Pub.App.MD5Encrypt32(ds.Tables[0].Rows[0]["pwd"].ToString()).ToUpper().Trim();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.wb1.Navigate(ds.Tables[0].Rows[0]["list"].ToString());
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            //123
            this.Execute();

            //HtmlElement buttonignore = this.wb1.Document.GetElementById("ignore");
            //buttonignore.InvokeMember("click");
        
        }


        private void Execute()
        {
            DataTable ldt_link; 
            DataTable ldt_sku ;
            try
            {
                ldt_link=App.SQLHelper.GetDataTable(this.ds.Tables[0].Rows[0]["conn"].ToString(), "select * from sku_link", "link");
                ldt_sku = App.SQLHelper.GetDataTable(this.ds.Tables[0].Rows[0]["conn"].ToString(), "select * from sku", "sku");
            }
            catch (Exception ex)
            {
                Collect_Pub.App.ErrLog(ex.ToString());
                Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
            , ds.Tables[0].Rows[0]["email_user"].ToString()
            , ds.Tables[0].Rows[0]["error_mail"].ToString()
            , ""
            , System.DateTime.Now.ToString() + "MMS服务器连接失败"
            , "Dear ALL:<br>" + System.DateTime.Now.ToString() + "MMS服务器连接失败，请及时处理服务器。订单采集系统会正常执行！" + ds.Tables[0].Rows[0]["login"].ToString()
            , ls
            , ds.Tables[0].Rows[0]["email_smtp"].ToString()
            , ds.Tables[0].Rows[0]["email_user"].ToString()
            , ds.Tables[0].Rows[0]["email_pwd"].ToString()
            );
                return;
            }
            ls_file.Clear();
            ls_print.Clear();
            ls.Clear();
           
            if (ds.Tables[0].Rows[0]["start"].ToString().ToUpper() == "TRUE")
            {
                Close();
            }


            

            //获取本地存放路径
            string lsdate = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string lsdir = System.IO.Path.Combine(ds.Tables[0].Rows[0]["add1"].ToString(), lsdate);
            if (System.IO.Directory.Exists(lsdir) == false)
            {
                System.IO.Directory.CreateDirectory(lsdir);
            }

            if (nFlag == true)
            {
                try
                {

                    //WebClient wc = new WebClient();
                    //wc.BaseAddress = "https://deep-supplier.apps.saic-gm.com/#/dashboard";
                    //wc.Encoding = Encoding.UTF8;
                    //HtmlDocument doc = new HtmlDocument();
                    //string html = wc.DownloadString("user/6971070.html");
                    //doc.LoadHtml(html);

                    while (wb1.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
                    {
                        System.Windows.Forms.Application.DoEvents();
                    }
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    string html = this.wb1.Document.All[1].InnerHtml;
                    doc.LoadHtml(html);



                    //3、获取订单清单
                    //HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    //doc.LoadHtml(this.wb1.Document.All[0].InnerHtml);
                    HtmlAgilityPack.HtmlNode nodes = doc.DocumentNode;
                  HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("//*[@id=\"pusListTab\"]/tbody/tr/td/a");
                   // HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("/html/body/div[4]/div[1]/div[2]/ul[1]");
                    if (node_tr==null)
                    {
                        return;
                    }
                    foreach (HtmlAgilityPack.HtmlNode item in node_tr)
                    {
                        Regex reg = new Regex(@"(\d+(\.\d+)?)", RegexOptions.None);
                        ls.Add(reg.Matches(item.OuterHtml)[0].Value);
                        System.Threading.Thread.Sleep(1000);
                    }
                    nLogin = 0;  //登陆成功后，重置
                   
                }
                catch (Exception ex)
                {
                   
                    string lsmsg = "";
                    if (nLogin>1)
                    {
                        ds.Tables[0].Rows[0]["start"] = "True";
                        ds.Tables[0].WriteXml(spath);
                        lsmsg = "登陆错误" + Convert.ToString((nLogin + 1)) + "次，系统已停止服务！";
                    }
                    else
                    {
                        lsmsg = "登陆错误" + Convert.ToString((nLogin + 1)) + "次，系统会继续登陆！";
                        this.Start();
                    }
                    
                    Collect_Pub.App.ErrLog(ex.ToString());
                    Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
                , ds.Tables[0].Rows[0]["email_user"].ToString()
                , ds.Tables[0].Rows[0]["error_mail"].ToString()
                , ""
                , lsdate + "登陆错误"
                , "Dear ALL:<br>" + lsdate + lsmsg + ds.Tables[0].Rows[0]["login"].ToString()
                , ls
                , ds.Tables[0].Rows[0]["email_smtp"].ToString()
                , ds.Tables[0].Rows[0]["email_user"].ToString()
                , ds.Tables[0].Rows[0]["email_pwd"].ToString()
                );
                    return;
                }
            }

            //5、解析详细页面内容
            DataTable ldt_head = new DataTable();
            ldt_head.Columns.Add("no");
            ldt_head.Columns.Add("receipt");
            ldt_head.Columns.Add("receipt_date");
            ldt_head.Columns.Add("remark");
            ldt_head.Columns.Add("key");


            DataTable ldt_detail = new DataTable();
            ldt_detail.Columns.Add("no");
            ldt_detail.Columns.Add("sku");
            ldt_detail.Columns.Add("sku_magna");
            ldt_detail.Columns.Add("qty");
            ldt_detail.Columns.Add("key");

            try
            {

                //4、根据订单清单获取详细页面,保存页面到本地
                for (int i = 0; i < ls.Count; i++)
                {

                    string lsfile = System.IO.Path.Combine(lsdir, "" + ls[i].ToString() + ".mht");
                    CDO.Message message = new CDO.MessageClass();
                    ADODB.Stream stream = null;
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    message.MimeFormatted = true;
                    message.CreateMHTMLBody(ds.Tables[0].Rows[0]["detail"].ToString().Replace("{0}", ls[i].ToString()), CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
                    stream = message.GetStream();
                    stream.SaveToFile(lsfile, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);
                    message = null;
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                    ls_file.Add(lsfile);
                }
               // 获取打印文件
                for (int i = 0; i < ls.Count; i++)
                {

                    string lsfile = System.IO.Path.Combine(lsdir, "" + i.ToString() + ".mht");
                    CDO.Message message = new CDO.MessageClass();
                    ADODB.Stream stream = null;
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    message.MimeFormatted = true;
                    message.CreateMHTMLBody(ds.Tables[0].Rows[0]["print"].ToString().Replace("{0}", ls[i].ToString()), CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
                    stream = message.GetStream();
                    stream.SaveToFile(lsfile, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);
                    message = null;
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                    ls_print.Add(lsfile);
                }
          
            
               
                for (int i = 0; i < ls_file.Count; i++)
                {
                    string ls_no="";
                    string ls_receipt_date="";
                    string ls_factory="";
                    string ls_remark="";
                    string ls_key="";
                    

                    string lshtml = System.IO.File.ReadAllText(ls_file[i], Encoding.GetEncoding("GB2312"));
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(lshtml);
                    HtmlAgilityPack.HtmlNode nodes = doc.DocumentNode;
                    HtmlAgilityPack.HtmlNodeCollection node_no = nodes.SelectNodes("//*[@face=\"C39P36DmTt\"]");
                    if (node_no.Count > 0)
                    {
                        ls_no = node_no[0].InnerText.ToString().Replace("*", "");
                    }
                    HtmlAgilityPack.HtmlNodeCollection node_receipt = nodes.SelectNodes("/html/body/table/tr/td/table[3]/tbody/tr");
                    if (node_receipt.Count >= 10)
                    {
                        string[] ls_receipt = node_receipt[1].InnerText.ToString().Split(new char[] { '\r', '\n' });
                        ls_factory = ls_receipt[10].ToString().Replace("\t", "").Replace("<br>", "").Trim();
                        ls_receipt = node_receipt[2].InnerText.ToString().Split(new char[] { '\r', '\n' });
                       // ls_receipt_date= ls_receipt[10].ToString().Replace("\t", "").Replace("&nbsp;&nbsp;", " ").Trim();//要求送货日期
                        ls_receipt_date = ls_receipt[5].ToString().Replace("\t", "").Replace("&nbsp;&nbsp;", " ").Trim();//要求送货日期
                        ls_receipt = node_receipt[8].InnerText.ToString().Split(new char[] { '\r', '\n' });
                        if (ls_receipt.Length >= 11)
                        {
                            ls_remark = ls_receipt[12].ToString().Replace("\t", "").Trim();//判断数组是否超出
                        }
                               ls_key = i.ToString();
                             DataRow ldr_head = ldt_head.NewRow();
                             ldr_head["key"] = ls_key;
                             ldr_head["no"] = ls_no;
                             ldr_head["receipt"] = ls_factory;
                             ldr_head["receipt_date"] = ls_receipt_date;
                             if (ls_remark!="")
                             {
                                 ldr_head["remark"] = ls_no + "_" + ls_remark;

                             }
                             else
                             {
                                 ldr_head["remark"] = "";
                             }
                             ldt_head.Rows.Add(ldr_head);

                             #region 订单不需要合并
                         //  DataRow[] ldrs = ldt_head.Select("receipt='" + ls_factory + "' and receipt_date='"+ls_receipt_date+"'");
                         //if (ldrs.Length ==0)//判断是否合并、不需要合并
                         //{
                         //    ls_key = ldrs[0]["key"].ToString();
                         //    ldrs[0]["no"] = ldrs[0]["no"].ToString()+"/" + ls_no.ToString();
                         //    if (ls_remark.ToString()!="")
                         //    {
                         //        ldrs[0]["remark"] = ldrs[0]["remark"].ToString() + "/" + ls_no.ToString()+ "_" + ls_remark;
                         //    }
                            
                         //}
                         //else
                         //{
                         //    ls_key = i.ToString();
                         //    DataRow ldr_head = ldt_head.NewRow();
                         //    ldr_head["key"] = ls_key;
                         //    ldr_head["no"] = ls_no;
                         //    ldr_head["receipt"] = ls_factory;
                         //    ldr_head["receipt_date"] = ls_receipt_date;
                         //    if (ls_remark!="")
                         //    {
                         //        ldr_head["remark"] = ls_no + "_" + ls_remark;

                         //    }
                         //    else
                         //    {
                         //        ldr_head["remark"] = "";
                         //    }
                         //    ldt_head.Rows.Add(ldr_head);

                             //}
                             #endregion

                         }
                   
                    HtmlAgilityPack.HtmlNodeCollection node_tr = nodes.SelectNodes("/html/body/table/tr/td/table[5]/tbody/tr");
                    string ls_sku="";
                    int ln_qty=0;
                    for (int j = 2; j < node_tr.Count; j++)
                    {

                        string lsvalue = node_tr[j].InnerText;
                        string[] lsvalues = lsvalue.ToString().Split(new char[] { '\r', '\n' });
                        if (lsvalues.Length > 7)
                        {
                           // ls_sku=lsvalues[4].Replace("\t", "").ToString().Trim();//解析字段调整
                            // ln_qty=Convert.ToInt32(lsvalues[8].Replace("\t", "").ToString().Trim());//解析字段调整
                            ls_sku = lsvalues[2].Replace("\t", "").ToString().Trim();//料号
                            ln_qty = Convert.ToInt32(lsvalues[9].Replace("\t", "").ToString().Trim());//数量

                            DataRow[] ldrs_detail=ldt_detail.Select("key='"+ls_key+"' and sku='"+ls_sku+"'");
                            if (ldrs_detail.Length>0)
                            {
                                ldrs_detail[0]["qty"] = Convert.ToInt32(ldrs_detail[0]["qty"]) + ln_qty;
                                
                            }else
	                        {
                                DataRow ldr_detail = ldt_detail.NewRow();
                                ldr_detail["no"] = node_no[0].InnerText.ToString().Replace("*", "");
                                ldr_detail["key"] = ls_key.ToString();
                                ldr_detail["sku"] = ls_sku;
                                ldr_detail["qty"] = ln_qty;
                                ldt_detail.Rows.Add(ldr_detail);

	                        }
                          
                        }

                    }
                    string lsfile = System.IO.Path.Combine(lsdir, ls_no + "--" + i.ToString() + ".mht");
                    System.IO.File.Copy(ls_file[i].ToString(), lsfile, true);
                    if (System.IO.File.Exists(ls_file[i].ToString()))
                    {
                        System.IO.File.Delete(ls_file[i].ToString());
                    }
                    ls_file[i] = lsfile;

                    string lsfile_print = System.IO.Path.Combine(lsdir, ls_no  + ".mht");
                    System.IO.File.Copy(ls_print[i].ToString(), lsfile_print, true);
                    if (System.IO.File.Exists(ls_print[i].ToString()))
                    {
                        System.IO.File.Delete(ls_print[i].ToString());
                    }
                    ls_print[i] = lsfile_print;


                }
               
            }
            catch (Exception ex)
            {
                Collect_Pub.App.ErrLog("4、5获取页面解析错误："+ex.ToString());
                Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
            , ds.Tables[0].Rows[0]["email_user"].ToString()
            , ds.Tables[0].Rows[0]["error_mail"].ToString()
            , ""
            , lsdate + "4、5获取页面解析错误"
            , "Dear ALL:" + lsdate + "4、5获取页面解析错误，系统会下次再次重新解析！" + ds.Tables[0].Rows[0]["login"].ToString()
            , ls
            , ds.Tables[0].Rows[0]["email_smtp"].ToString()
            , ds.Tables[0].Rows[0]["email_user"].ToString()
            , ds.Tables[0].Rows[0]["email_pwd"].ToString()
            );
                return;
                
            }

                //8、发送邮件
                if (ds.Tables[0].Rows[0]["send_email"].ToString().Trim() != "")
                {
                    try
                    {
                         Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
                    , ds.Tables[0].Rows[0]["email_name"].ToString()
                    , ds.Tables[0].Rows[0]["send_email"].ToString().Trim()
                    , ""
                    , ds.Tables[0].Rows[0]["email_title"].ToString() + "-" + lsdate
                    , ds.Tables[0].Rows[0]["email_body"].ToString()
                    , ls_print
                    , ds.Tables[0].Rows[0]["email_smtp"].ToString()
                    , ds.Tables[0].Rows[0]["email_user"].ToString()
                    , ds.Tables[0].Rows[0]["email_pwd"].ToString()
                    );
                        
                    }
                    catch (Exception ex)
                    {
                        
                         Collect_Pub.App.ErrLog("8发送邮件失败："+lsdir+"-------"+ex.ToString());
         
                        return;
                    }

                }


                //6、生成出货单
                List<string> ls_sql = new List<string>();
                try
                {
                   
                if (this.ds.Tables[0].Rows[0]["conn"].ToString() != "")
                {
                    for (int i = 0; i < ldt_head.Rows.Count; i++)
                    {
                       
                        string lsfactory = "001";
                        string lswhseid = "wh1";
                        if (this.ds.Tables[0].Rows[0]["factory"].ToString() == "KS")
                        {
                            lsfactory = "001";
                            lswhseid = "wh1";
                        }
                        else if (this.ds.Tables[0].Rows[0]["factory"].ToString() == "KSJC")
                        {
                            lsfactory = "023";
                            lswhseid = "wh3";
                        }
                        string lsorderkey = App.SQLHelper.ExecuteScalar(this.ds.Tables[0].Rows[0]["conn"].ToString(), CommandType.Text, "DECLARE @key varchar(50) exec pro_GetOrderNo '" + lswhseid + "','" + lsfactory + "OB','ORDERKEY','出货单号',@key OUTPUT select @key as orderkey ", new System.Data.SqlClient.SqlParameter("", "")).ToString();//调用存储过程pro_GetOrderNo生成出货单号
                        string lsSql = "insert into orders(whseid,orderkey,customer_code,delivery_order,status,type,priority,data_from,requestshipdate,grossweight";
                        lsSql += ",netweight,cube,plt,ctn,pcs,udf1,udf2,udf3,udf4,remark,product,addwho,adddate) values ";
                        lsSql += "('" + lswhseid + "','" + lsorderkey + "','" + this.ds.Tables[0].Rows[0]["factory"].ToString() + "','" + ldt_head.Rows[i]["no"].ToString() + "','01','01','02'";
                        lsSql += ",'采集新增','" + ldt_head.Rows[i]["receipt_date"].ToString() + "'";
                        lsSql += ", 0,0,0,0,0,0";
                        lsSql += ",'','','',''";
                        lsSql += ",'" + ldt_head.Rows[i]["remark"].ToString() + "','1','System','" + System.DateTime.Now.ToString() + "')";
                        ls_sql.Add(lsSql);
                        DataRow[] ldrs = ldt_detail.Select("key='" + ldt_head.Rows[i]["key"].ToString() + "'");
                        for (int j = 0; j < ldrs.Length; j++)
                        {
                            string lssku = "";
                            string lssku_descr = "";
                            string lssku_unit = "";
                            string lsflag = ldrs[j]["no"].ToString().Split('-')[0].ToString();
                            DataRow[] ldrs_link = ldt_link.Select("customer_sku='" + ldrs[j]["sku"].ToString() + "' and factory_code='" + lsflag + "'");
                            if (ldrs_link.Length == 1)
                            {
                                lssku = ldrs_link[0]["sku"].ToString();
                                DataRow[] ldrs_sku = ldt_sku.Select("sku='" + lssku + "' and whseid='" + lswhseid + "'");
                                if (ldrs_sku.Length == 1)
                                {
                                    lssku_descr = ldrs_sku[0]["description"].ToString();
                                    lssku_unit = ldrs_sku[0]["unit"].ToString();
                                }
                            }
                            else
                            {
                                lssku = ldrs[j]["sku"].ToString();
                            }

                            lsSql = "insert into orderdetail(whseid,orderkey,line_no,customer_code,sku,skudescr,status,pre_qty,act_qty,allocated_qty,picked_qty,unshiped_qty,lottable01,lottable02,lottable03,lottable04,lottable05,lottable06,lottable07,lottable08,lottable09,lottable10";
                            lsSql += ",uom,viceuom,udf1,udf2,udf3,udf4,remark,addwho,adddate) values ";
                            lsSql += "('" + lswhseid + "','" + lsorderkey + "','" + (j + 1).ToString("D5") + "','" + this.ds.Tables[0].Rows[0]["factory"].ToString() + "','" + lssku + "','" + lssku_descr + "','01'";
                            lsSql += "," + ldrs[j]["qty"].ToString() + ",0,0,0," + ldrs[j]["qty"].ToString() + "";
                            lsSql += ",'','','','','','','" + ldrs[j]["sku"].ToString() + "'";
                            lsSql += " ,'" + ldt_head.Rows[i]["receipt"].ToString() + "','','','" + lssku_unit + "','','','','',''";
                            lsSql += ",'','System','" + System.DateTime.Now.ToString() + "')";
                            ls_sql.Add(lsSql);
                        }
                    }

                    App.SQLHelper.ExecuteSQLScriptLists(ls_sql, this.ds.Tables[0].Rows[0]["conn"].ToString());
                }
                
                }
                catch (Exception ex)
                {
                   

                        Collect_Pub.App.ErrLog("6、生成出货单错误：" + ex.ToString());
                        Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
                    , ds.Tables[0].Rows[0]["email_user"].ToString()
                    , ds.Tables[0].Rows[0]["error_mail"].ToString()
                    , ""
                    , lsdate + "6、生成出货单错误"
                    , "Dear ALL:" + lsdate + "6、生成出货单错误！" + ds.Tables[0].Rows[0]["login"].ToString()
                    , ls_print
                    , ds.Tables[0].Rows[0]["email_smtp"].ToString()
                    , ds.Tables[0].Rows[0]["email_user"].ToString()
                    , ds.Tables[0].Rows[0]["email_pwd"].ToString()
                    );
                        return;
                   
                }
                



                    //7、保存页面到共享文件夹
                try
                {

                    if (ds.Tables[0].Rows[0]["add2"].ToString().Trim() != "")
                    {
                        string lspath2 = System.IO.Path.Combine(ds.Tables[0].Rows[0]["add2"].ToString().Trim(), lsdate);
                        if (System.IO.Directory.Exists(lspath2) == false)
                        {
                            System.IO.Directory.CreateDirectory(lspath2);
                        }

                        for (int i = 0; i < ls_print.Count; i++)
                        {
                            string lsfile2 = System.IO.Path.Combine(lspath2, System.IO.Path.GetFileName(ls[i]).ToString());
                            System.IO.File.Copy(ls_print[i], lsfile2, true);
                        }

                    }
                   
                }
                catch (Exception ex)
                {
                   
                      Collect_Pub.App.ErrLog("7、保存页面到共享文件夹错误：" + ex.ToString());
                    Collect_Pub.App.Mail_Send(ds.Tables[0].Rows[0]["email_user"].ToString()
                , ds.Tables[0].Rows[0]["email_user"].ToString()
                , ds.Tables[0].Rows[0]["error_mail"].ToString()
                , ""
                , lsdate + "7、保存页面到共享文件夹错误"
                , "Dear ALL:" + lsdate + "7、保存页面到共享文件夹错误,系统会继续执行！" + ds.Tables[0].Rows[0]["login"].ToString()
                , ls_print
                , ds.Tables[0].Rows[0]["email_smtp"].ToString()
                , ds.Tables[0].Rows[0]["email_user"].ToString()
                , ds.Tables[0].Rows[0]["email_pwd"].ToString()
                );
                    return;
                }


               
                    //9.将网页设为已阅
                    for (int i = 0; i < ls.Count; i++)
                    {
                        this.wb1.Navigate(ds.Tables[0].Rows[0]["detail"].ToString().Replace("{0}", ls[i].ToString()));
                    }
                    //10.再次加载订单清单
                    this.wb1.Navigate(ds.Tables[0].Rows[0]["list"].ToString());
                    nFlag = true;
                    //11.删除ls_file文件
                    for (int i = 0; i < ls_file.Count; i++)
                    {
                        if (System.IO.File.Exists(ls_file[i].ToString()))
                        {
                            System.IO.File.Delete(ls_file[i]);
                        }
                    } 

        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.Execute();
            MessageBox.Show("执行成功!");
        }

        private void wb1_NewWindow(object sender, CancelEventArgs e)
        {
           // e.Cancel = true;
          
        }

        private void btnjump_Click(object sender, EventArgs e)
        {
            this.wb1.Navigate(ds.Tables[0].Rows[0]["list"].ToString());
            //int a = 0;
            //string b = "a";
            //try
            //{
            //    a =Convert.ToInt32(b);

            //}
            //catch (Exception ex)
            //{
                
            //    try
            //    {
            //        a = Convert.ToInt32("cc");
            //        return;
            //    }
            //    catch (Exception ex1)
            //    {
            //        MessageBox.Show("b");
            //        return;
            //    }
                
            //}
            
        }

        

    }
}